package columnd

import (
	"github.com/globalsign/mgo"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd"
	"gogs.xiaoyuanjijiehao.com/antlinker/antcms/ddd/repo/mgorepo"

	ccolumnd "gogs.xiaoyuanjijiehao.com/antlinker/antcms/core/columnd"
)

// param 参数
type param struct {
	Pcode string      `bson:"pcode"` // 参数编码
	Name  string      `bson:"name"`  // 显示名称
	Typ   string      `bson:"typ"`   // 数据类型
	Value interface{} `bson:"value"` // 值 不同类型支持的值不同
}

func (p param) To() ccolumnd.Param {
	return ccolumnd.Param{
		Pcode: p.Pcode,
		Name:  p.Name,
		Typ:   p.Typ,
		Value: p.Value,
	}
}

type params []param

func (p params) To() (out []ccolumnd.Param) {
	for _, v := range p {
		out = append(out, v.To())
	}
	return
}

// @collname 栏目扩展类型集合(i_extraType)
type collExtraType struct {
	Code   string `bson:"_id"`    // 编号
	Name   string `bson:"name"`   // 名称
	Params params `bson:"params"` // 可以配置参数
}

func (c collExtraType) CollID() string {
	return c.Code
}
func (collExtraType) CollName() string {
	return collNameExtraType
}
func (c collExtraType) IsCache() bool {
	return c.Code != ""
}
func (c collExtraType) ToAggregate() ddd.Aggregate {
	return c.ToExtraTypeAggregte()
}
func (c collExtraType) ToExtraTypeAggregte() *ccolumnd.ExtraTypeAggregte {
	return &ccolumnd.ExtraTypeAggregte{
		ExtraType: ccolumnd.ExtraType{
			Code:   c.Code,
			Name:   c.Name,
			Params: c.Params.To(),
		},
	}

}

type extraTypeRepo struct {
	mgorepo.BaseRepo
}

func (r *extraTypeRepo) LoadAll(ctx ddd.Context) (result []ccolumnd.ExtraType, e error) {
	var coll []collExtraType
	err := r.DBQuery(ctx, collNameExtraType, nil, nil, nil, &coll)
	if err != nil {
		if err == mgo.ErrNotFound {
			return nil, nil
		}
		return nil, err
	}
	for _, v := range coll {
		result = append(result, v.ToExtraTypeAggregte().ExtraType)
	}
	return
}
func (r *extraTypeRepo) LoadOne(ctx ddd.Context, code string) (ea *ccolumnd.ExtraType, err error) {
	a, err := r.GetByCollAggregate(ctx, &collExtraType{Code: code})
	if err != nil {
		return nil, err
	}
	tmp := a.(*ccolumnd.ExtraTypeAggregte)
	return &tmp.ExtraType, nil
}
